# -*- coding: utf-8 -*-

import os
import configparser
import threading

from app.hepler.helper import root_path


class Config:
    """
    配置文件操作类--单列模式
    使用 c = Config.init()
    """

    _instance_lock = threading.Lock()

    def __init__(self):
        # 指定配置文件目录
        self.config_path = os.path.join(root_path(), "config")

    def __new__(cls, *args, **kwargs):
        if not hasattr(cls, '_instance'):
            with cls._instance_lock:
                if not hasattr(cls, '_instance'):
                    cls._instance = object.__new__(cls)

                    # 实例化对象后增加私有属性(必须放在后面)
                    cls._config = cls()._get_config()

        return cls._instance

    def _get_config(self):
        """
        获取configparser对象实例
        """

        # 初始化config
        config = configparser.ConfigParser()

        # 循环遍历config文件夹加载所有配置文件
        for dir_path, dir_names, file_names in os.walk(self.config_path):
            for config_file in file_names:
                if config_file.find("ini") == -1:
                    continue

                config_path = dir_path + "/" + config_file
                config.read(config_path, encoding="utf8")

        return config


    @classmethod
    def init(cls):
        """初始化返回原生config，可以直接调用使用"""
        return cls()._config
